import { getSpareList } from '@/api/goodsInfo'
import { ref } from 'vue'

/**
 * 获取备件列表服务
 */
export default function () {
  const getSparePartListLoading = ref(false)
  const getSparePartListParam = ref<GoodAPIRequest.GetSparePartListParam>({
    page: 1,
    limit: 100,
    goodsIdList: [],
    goodsType: '',
    brandId: '',
    unitId: '',
    typeId: '',
    typeTwoId: '',
    typeThreeId: '',
    source: '',
    keyword: '',
    coreMaterials: false,
    ascriptionType: '',
  })
  const sparePartList = ref<Array<GoodAPIResponse.SparePartListItem>>([])
  const total = ref(0)

  const resetGetSparePartListParam = () => {
    getSparePartListParam.value = {
      page: 1,
      limit: 100,
      goodsIdList: [],
      goodsType: '',
      brandId: '',
      unitId: '',
      typeId: '',
      typeTwoId: '',
      typeThreeId: '',
      source: '',
      keyword: '',
      coreMaterials: false,
      ascriptionType: '',
    }
  }

  const getSparePartList = async () => {
    try {
      getSparePartListLoading.value = true
      const res = await getSpareList(getSparePartListParam.value)
      getSparePartListLoading.value = false
      if (res.data.code === 20000) {
        total.value = Number(res.data.data.total)
        sparePartList.value = res.data.data.rows
        return ''
      }

      return res.data.message
    } catch (error) {
      getSparePartListLoading.value = false
      return '获取备件列表失败，请稍后重试'
    }
  }

  return {
    total,
    sparePartList,
    getSparePartListParam,
    getSparePartListLoading,
    getSparePartList,
    resetGetSparePartListParam,
  }
}
